import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Form, Input, InputNumber, message, Modal, Select } from 'antd';
import React, { useState } from 'react';

import api from '@/apis/api';
import { Logger } from '@/components/useLogger';

const { Option } = Select;

interface KeyCreateModalProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const KeyCreateModal: React.FC<KeyCreateModalProps> = ({ visible, setVisible }) => {
  const [form] = Form.useForm();
  const queryClient = useQueryClient();
  const [keyType, setKeyType] = useState<number>(0);

  const [keyLengths, setKeyLengths] = useState<number[]>([]);

  const handleKeyTypeChange = (value: number) => {
    let lengths: number[] = [];
    switch (value) {
      case 0:
        lengths = [256];
        break;
      case 1:
        lengths = [256];
        break;
      case 2:
        lengths = [1024, 2048];
        break;
      case 3:
        lengths = [1024, 2048];
        break;
      case 4:
        lengths = [128, 256];
        break;
      default:
        lengths = [];
    }
    setKeyType(value);
    setKeyLengths(lengths);
  };

  const CreateKey = useMutation({
    mutationFn: (params: any) => api.CreateKey(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('创建成功');
      } else {
        message.error(`创建失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('创建失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getKeyManageData'] }),
    mutationKey: ['getKeyManageData'],
  });

  const handleCreateOk = async () => {
    await form.validateFields();
    const { keyPinCode, keyIndex, keyType, keyLength } = form.getFieldsValue();

    CreateKey.mutate({
      pincode: keyPinCode,
      key_index: keyIndex ?? -1,
      key_type: keyType,
      bits: keyLength,
    });
    form.resetFields();
    setVisible(false);
  };

  const handleCreateCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <>
      <Modal
        title="密钥创建"
        open={visible}
        onOk={handleCreateOk}
        onCancel={handleCreateCancel}
        cancelText="取消"
        okText="确定"
        destroyOnClose
        // okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form form={form} preserve={false} autoComplete="off">
          <div style={{ marginBottom: '10px' }}>
            <span style={{ marginRight: '10px' }}>密钥访问控制码:</span>
            <div style={{ display: 'inline-block' }}>
              <Form.Item
                name="keyPinCode"
                style={{
                  marginBottom: 0,
                }}
                rules={[{ required: true, message: '请输入密钥访问控制码！' }]}
              >
                <Input.Password
                  placeholder="请输入密钥访问控制码"
                  autoComplete="new-password"
                />
              </Form.Item>
            </div>
          </div>
          <div style={{ marginBottom: '10px' }}>
            <span style={{ marginRight: '10px' }}>确认密钥访问控制码:</span>
            <div style={{ display: 'inline-block' }}>
              <Form.Item
                name="reapetPinCode"
                style={{
                  marginBottom: 0,
                }}
                rules={[
                  ({ getFieldValue }) => ({
                    validator(rule, value) {
                      if (!value || getFieldValue('keyPinCode') === value) {
                        return Promise.resolve(rule);
                      }
                      return Promise.reject('两次密钥访问控制码不同！');
                    },
                  }),
                  { required: true, message: '请再输入密钥访问控制码!' },
                ]}
              >
                <Input.Password placeholder="请再输入密钥访问控制码!" />
              </Form.Item>
            </div>
          </div>

          <div style={{ marginBottom: '10px', display: 'flex' }}>
            <span style={{ marginRight: '10px', marginTop: 4 }}>密钥类型:</span>
            <Form.Item
              name="keyType"
              style={{
                marginBottom: 0,
              }}
              rules={[{ required: true, message: '请选择密钥类型！' }]}
            >
              <Select
                placeholder={'请选择密钥类型'}
                style={{ width: 180 }}
                onChange={handleKeyTypeChange}
                allowClear
              >
                <Option value={0}>SM2加密密钥</Option>
                <Option value={1}>SM2签名密钥</Option>
                <Option value={2}>RSA加密密钥</Option>
                <Option value={3}>RSA签名密钥</Option>
                <Option value={4}>密钥加密密钥</Option>
              </Select>
            </Form.Item>
          </div>

          <div style={{ marginBottom: '10px', display: 'flex' }}>
            <span style={{ marginRight: '10px', marginTop: 4 }}>密钥长度:</span>
            <Form.Item
              name="keyLength"
              style={{
                marginBottom: 0,
              }}
              rules={[{ required: true, message: '请选择密钥长度！' }]}
              dependencies={['keyType']}
            >
              <Select placeholder={'请选择密钥长度'} style={{ width: 180 }} allowClear>
                {/* 根据选择的密钥类型，提供长度选项 */}
                {keyLengths.map((length) => (
                  <Option key={length} value={length}>{`${length}位`}</Option>
                ))}
              </Select>
            </Form.Item>
          </div>

          <div style={{ marginBottom: '10px' }}>
            <span style={{ marginRight: '10px' }}>密钥索引:</span>
            <div style={{ display: 'inline-block' }}>
              <Form.Item
                name="keyIndex"
                style={{
                  marginBottom: 0,
                }}
                rules={[{ required: false, message: '请输入密钥索引！' }]}
              >
                <InputNumber
                  placeholder={`从${keyType === 4 ? 1 : 0}开始`}
                  min={keyType === 4 ? 1 : 0}
                  max={256}
                />
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>
    </>
  );
};

export default KeyCreateModal;
